package br.com.unibratec.util;

import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import br.com.unibratec.negocio.Evento;
import br.com.unibratec.receiver.AgendadorReceiver;

public class AgendaUtil {

	private Activity activity;
	private Context applicationContext;
	private static AgendaUtil agendaUtil;

	private AgendaUtil() {
	}

	public static AgendaUtil getInstace() {
		if (agendaUtil == null) {
			agendaUtil = new AgendaUtil();
		}
		return agendaUtil;
	}

	public AgendaUtil setConfig(Activity activity, Context contexto) {
		this.activity = activity;
		this.applicationContext = contexto;
		return agendaUtil;
	}

	public void agendar(Evento ev) {
		this.agendar(ev, (int) ev.getId());
	}

	public void agendar(Evento ev, int lastId) {
		long agenda = ev.getData().getTime();
		Intent it = new Intent(this.activity, AgendadorReceiver.class);
		it.putExtra("notifcacaoId", lastId);
		it.putExtra("evento", ev);
		PendingIntent pit = PendingIntent.getBroadcast(this.activity, lastId, it, 0);
		AlarmManager alarm = (AlarmManager) this.activity.getSystemService(Context.ALARM_SERVICE);
		alarm.set(AlarmManager.RTC_WAKEUP, agenda, pit);
	}

	public void cancelarAgendamento(int id) {
		NotificationManager nm = (NotificationManager) this.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
		nm.cancel(id);
		AlarmManager alarm = (AlarmManager) this.activity.getSystemService(Context.ALARM_SERVICE);
		Intent it = new Intent(this.activity, AgendadorReceiver.class);
		alarm.cancel(PendingIntent.getBroadcast(this.activity, id, it, 0));
	}

	public void atualizarNotificacoes(List<Evento> eventos) {
		for (Evento evento : eventos) {
			this.agendar(evento);
		}
	}

}
